import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user_model.dart';
import '../services/user_service.dart';

part 'auth_store.g.dart';

class AuthStore = _AuthStore with _$AuthStore;

abstract class _AuthStore with Store {
  final UserService _userService = UserService();
  static const String _loggedInUserIdKey = 'loggedInUserId';

  @observable
  UserModel? currentUser;

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @computed
  bool get isLoggedIn => currentUser != null;

  // 初始化方法，用于从SharedPreferences恢复登录状态
  Future<void> init() async {
    isLoading = true;
    try {
      await _loadSavedUser();
    } catch (e) {
      errorMessage = 'Failed to restore login session: ${e.toString()}';
    } finally {
      isLoading = false;
    }
  }

  // 从SharedPreferences中恢复用户登录状态
  Future<void> _loadSavedUser() async {
    final prefs = await SharedPreferences.getInstance();
    final userId = prefs.getString(_loggedInUserIdKey);

    if (userId != null && userId.isNotEmpty) {
      currentUser = _userService.getUserById(userId);
    }
  }

  // 保存用户ID到SharedPreferences
  Future<void> _saveUserId(String userId) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_loggedInUserIdKey, userId);
  }

  // 清除SharedPreferences中的用户ID
  Future<void> _clearSavedUserId() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_loggedInUserIdKey);
  }

  @action
  Future<bool> login(String username, String password) async {
    isLoading = true;
    errorMessage = null;

    try {
      final user = _userService.authenticate(username, password);
      if (user != null) {
        currentUser = user;
        // 保存用户ID到SharedPreferences
        await _saveUserId(user.id);
        isLoading = false;
        return true;
      } else {
        errorMessage = 'Username or password error';
        isLoading = false;
        return false;
      }
    } catch (e) {
      errorMessage = 'Login failed: ${e.toString()}';
      isLoading = false;
      return false;
    }
  }

  @action
  Future<void> logout() async {
    // 清除SharedPreferences中保存的用户ID
    await _clearSavedUserId();
    currentUser = null;
  }

  @action
  Future<bool> register({
    required String username,
    required String password,
    required String name,
    required String email,
  }) async {
    isLoading = true;
    errorMessage = null;

    try {
      // 检查用户名是否已存在
      final existingUser = _userService.getUserByUsername(username);
      if (existingUser != null) {
        errorMessage = 'Username already exists';
        isLoading = false;
        return false;
      }

      // 创建新用户
      currentUser = await _userService.createUser(
        username: username,
        password: password,
        name: name,
        email: email,
      );

      // 保存用户ID到SharedPreferences
      if (currentUser != null) {
        await _saveUserId(currentUser!.id);
      }

      isLoading = false;
      return true;
    } catch (e) {
      errorMessage = 'Register failed: ${e.toString()}';
      isLoading = false;
      return false;
    }
  }

  @action
  Future<void> updateProfile({
    String? name,
    String? email,
    String? avatar,
    String? description,
  }) async {
    if (currentUser == null) return;

    isLoading = true;
    errorMessage = null;

    try {
      if (name != null) currentUser!.name = name;
      if (email != null) currentUser!.email = email;
      if (avatar != null) currentUser!.avatar = avatar;
      if (description != null) currentUser!.description = description;

      await _userService.updateUser(currentUser!);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Update failed: ${e.toString()}';
      isLoading = false;
    }
  }
}
